#pragma once

#include <functional>
#include <pthread.h>
#include "socket.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"
static const int gport = 8888;

using service_io_t = std::function<std::string(std::string&)>;

class TcpServer
{
private:
    service_io_t _service;
    int _sockfd;
    uint16_t _port;
    SockSPtr _listen_sock;
    bool _is_running;

public:
    class ThreadData
    {
    public:
        SockSPtr _sockfd;
        TcpServer *_self;
        InetAddr _addr;

    public:
        ThreadData(SockSPtr sockfd, TcpServer *self, const InetAddr &addr) : _sockfd(sockfd), _self(self), _addr(addr)
        {
        }
    };
    TcpServer(service_io_t service, uint16_t port)
        :_service(service)
        ,_port(port)
        ,_listen_sock(std::make_shared<TcpSocket>()) 
        ,_is_running(false)
    {
        _listen_sock->buildListenSocket(_port);
    }

    void loop()
    {
        _is_running = true;
        while (true)
        {
            InetAddr client;
            SockSPtr newsock = _listen_sock->acceptSocket(&client);

            if (newsock == nullptr)
                continue;
            LOG(INFO, "get a new link, client info: %s", client.AddrStr().c_str(), newsock->Sockfd());

            // TODO
            // 多线程
            pthread_t tid;
            ThreadData *td = new ThreadData(newsock, this, client);
            pthread_create(&tid, nullptr, Execute, td); // 新线程进行分离
        }
        _is_running = false;
    }
    static void *Execute(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        // 接收
        std::string requeststr; // --- 不保证能读取到一个完整的请求
        ssize_t n = td->_sockfd->Recv(&requeststr);
        // 发送
        if (n > 0)
        {
            std::string responsestr = td->_self->_service(requeststr);
            td->_sockfd->Send(responsestr);
        }
        td->_sockfd->Close();
        delete td;
        return nullptr;
    }
};